package com.dsz.du.mealbooking.dao;

import java.util.List;

import javax.jdo.PersistenceManager;
import com.dsz.du.gaesuport.MyPersistenceManagerFactory;


public class BaseDao {
	
	
	/**
	 * 基本操作之保存
	 * @param model
	 */
	public void saveModel(Object model) {
		PersistenceManager pm = MyPersistenceManagerFactory.getInstance().getPersistenceManager();		
		try {
			pm.makePersistent(model);
		} finally {
			if (pm.isClosed() == false){
				close(pm);
			}
		}
	}
	
	/**
	 * 基本操作之删除
	 * @param model
	 */
	public void deleteModel(Object model) {
		PersistenceManager pm = MyPersistenceManagerFactory.getInstance().getPersistenceManager();		
		try {
			pm.deletePersistent(model);
		} finally {
			if (pm.isClosed() == false){
				close(pm);
			}
		}
	}
	
	/**
	 * 基本操作之读取Model
	 * @param model
	 */
	public Object getModelById(Object id) {
		PersistenceManager pm = MyPersistenceManagerFactory.getInstance().getPersistenceManager();		
		Object model = null;
		try {
			model = pm.getObjectById(id);
		} finally {
			if (pm.isClosed() == false){
				close(pm);
			}
		}
		return model;
	}	
	
	/**
	 * 基本操作之执行查询
	 * @param model
	 */
	public List excuteQuery(String queryString) {
		PersistenceManager pm = MyPersistenceManagerFactory.getInstance().getPersistenceManager();		
		List models =  null;
		try {
			models =  (List) pm.newQuery(queryString).execute();
		} finally {
			if (pm.isClosed() == false){
				close(pm);
			}
		}
		return models;
	}
	
	/**
	 * 基本操作之执行 查询
	 * @param model
	 */
	public Object excuteSingleQuery(String queryString) {
		PersistenceManager pm = MyPersistenceManagerFactory.getInstance().getPersistenceManager();		
		List models =  null;
		Object model = null;
		try {
			models =  (List) pm.newQuery(queryString).execute();
			if (models.size() > 0){
				model = models.get(0);
			}
			return model;			
		} finally {
			if (pm.isClosed() == false){
				close(pm);
			}
		}

	}

	private void close(PersistenceManager pm) {
		pm.close();
		
	}	
}
